Aula 3 - Modificando Variáveis

0.1

Na aula de hoje uma das funções mais importantes durante o processo de processamento de dados, o mutate

Ele tem como objetivo criar novas colunas ou alterar colunas já existentes

Possui a seguinte sintaxe

# Criando nova variável
dados |>
  dplyr::mutate(nova_variável = função(variável_existente))
                
# Alterando variável já existente

dados |>
  dplyr::mutate(variável_existente = função(variável_existente))

1 Exemplos

1.1 Ações - GAFA

tsibbledata::gafa_stock |>
  dplyr::filter(Symbol == 'AAPL') |>
  autoplot(Volume)

tsibbledata::gafa_stock |>
  janitor::clean_names() |>
  dplyr::filter(symbol == 'AAPL') |>
  dplyr::mutate(log_volume = 1/(volume)) |>
  autoplot(log_volume)

tsibbledata::gafa_stock |>
  as_tibble() |>
  janitor::clean_names() |>
  dplyr::mutate(date = tsibble::yearweek(date))
# A tibble: 5,032 x 8
   symbol     date  open  high   low close adj_close    volume
   <chr>    <week> <dbl> <dbl> <dbl> <dbl>     <dbl>     <dbl>
 1 AAPL   2014 W01  79.4  79.6  78.9  79.0      67.0  58671200
 2 AAPL   2014 W01  79.0  79.1  77.2  77.3      65.5  98116900
 3 AAPL   2014 W02  76.8  78.1  76.2  77.7      65.9 103152700
 4 AAPL   2014 W02  77.8  78.0  76.8  77.1      65.4  79302300
 5 AAPL   2014 W02  77.0  77.9  77.0  77.6      65.8  64632400
 6 AAPL   2014 W02  78.1  78.1  76.5  76.6      65.0  69787200
 7 AAPL   2014 W02  77.1  77.3  75.9  76.1      64.5  76244000
 8 AAPL   2014 W03  75.7  77.5  75.7  76.5      64.9  94623200
 9 AAPL   2014 W03  76.9  78.1  76.8  78.1      66.1  83140400
10 AAPL   2014 W03  79.1  80.0  78.8  79.6      67.5  97909700
# i 5,022 more rows
## Pronto para um group_by
tsibbledata::gafa_stock |>
  as_tibble() |>
  janitor::clean_names() |>
    dplyr::mutate(ano = lubridate::epiyear(date),
                  mes = lubridate::month(date)) |>
  dplyr::filter(ano == 2014,
                symbol == 'AAPL')
# A tibble: 253 x 10
   symbol date        open  high   low close adj_close    volume   ano   mes
   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>     <dbl> <dbl> <dbl>
 1 AAPL   2014-01-02  79.4  79.6  78.9  79.0      67.0  58671200  2014     1
 2 AAPL   2014-01-03  79.0  79.1  77.2  77.3      65.5  98116900  2014     1
 3 AAPL   2014-01-06  76.8  78.1  76.2  77.7      65.9 103152700  2014     1
 4 AAPL   2014-01-07  77.8  78.0  76.8  77.1      65.4  79302300  2014     1
 5 AAPL   2014-01-08  77.0  77.9  77.0  77.6      65.8  64632400  2014     1
 6 AAPL   2014-01-09  78.1  78.1  76.5  76.6      65.0  69787200  2014     1
 7 AAPL   2014-01-10  77.1  77.3  75.9  76.1      64.5  76244000  2014     1
 8 AAPL   2014-01-13  75.7  77.5  75.7  76.5      64.9  94623200  2014     1
 9 AAPL   2014-01-14  76.9  78.1  76.8  78.1      66.1  83140400  2014     1
10 AAPL   2014-01-15  79.1  80.0  78.8  79.6      67.5  97909700  2014     1
# i 243 more rows

2 Funções Auxiliares

2.1 dplyr::case_when()

A função case_when funciona como um if-else, porém sendo uma função vetorizada

Ela é chamada da seguinte forma

dados |>
  dplyr::mutate(
    nova_variável = 
      dplyr::case_when(
        valor_variavel % condição_1 ~  valor_a_receber_1,
        valor_variavel % condição_2 ~ valor_a_receber_1,
        ...,
        valor_variavel % condição_n ~ valor_a_receber_n
        )
    )
tsibbledata::gafa_stock |>
  tibble::as_tibble() |>
  janitor::clean_names() |>
  dplyr::filter(symbol == 'GOOG') |>
  dplyr::mutate(vol_pad = volume |> scale()) |>
  dplyr::mutate(
    cat_vol = 
      case_when(vol_pad <= -1 ~ 'baixo',
                vol_pad > -1 & vol_pad <=1 ~ 'medio',
                vol_pad > 1 ~ 'alto'
                )
    )
# A tibble: 1,258 x 10
   symbol date        open  high   low close adj_close  volume vol_pad[,1]
   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>   <dbl>       <dbl>
 1 GOOG   2014-01-02  554.  555.  551.  553.      553. 3666400        1.56
 2 GOOG   2014-01-03  554.  555.  549.  549.      549. 3355000        1.28
 3 GOOG   2014-01-06  553.  556.  550.  555.      555. 3561600        1.46
 4 GOOG   2014-01-07  559.  566.  557.  566.      566. 5138400        2.87
 5 GOOG   2014-01-08  569.  570.  563.  567.      567. 4514100        2.31
 6 GOOG   2014-01-09  568.  568.  559.  561.      561. 4196000        2.03
 7 GOOG   2014-01-10  566.  566.  557.  561.      561. 4314700        2.13
 8 GOOG   2014-01-13  560.  570.  555.  558.      558. 4869100        2.63
 9 GOOG   2014-01-14  565.  572.  560.  571.      571. 4997400        2.74
10 GOOG   2014-01-15  573.  574.  568.  571.      571. 3925700        1.79
# i 1,248 more rows
# i 1 more variable: cat_vol <chr>

2.2 dplyr::across()

Aplicar uma função em 2 ou mais colunas em uma ‘tacada só’

Ela é chamada da seguinte forma

dados |>
  dplyr::mutate(
    dplyr::across(
      c(var1, var2), 
      ~função(.)
      )
    )

dados |>
  dplyr::mutate(
    dplyr::across(
      condição, 
      ~função(.)
      )
    )

3 SRAG - Datasus

Código Município, Código UF, Idade, comorbidade, teve SRAGS, óbito

df_srag = readr::read_csv2(here::here('./conjunto_de_dados/srag_2023.csv')) 
i Using "','" as decimal and "'.'" as grouping mark. Use `read_delim()` for more control.
Warning: One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat)
Rows: 226763 Columns: 173
-- Column specification --------------------------------------------------------
Delimiter: ";"
chr (61): DT_NOTIFIC, DT_SIN_PRI, SG_UF_NOT, ID_REGIONA, ID_MUNICIP, ID_UNID...
dbl (98): SEM_NOT, SEM_PRI, CO_REGIONA, CO_MUN_NOT, CO_UNI_NOT, NU_IDADE_N, ...
lgl (14): SURTO_SG, FLUASU_OUT, FLUBLI_OUT, PCR_PARA2, PCR_PARA4, PAIS_VGM, ...

i Use `spec()` to retrieve the full column specification for this data.
i Specify the column types or set `show_col_types = FALSE` to quiet this message.
df_srag = df_srag |>
  select(CO_MUN_NOT, SG_UF, DT_NOTIFIC, CS_SEXO, NU_IDADE_N, FATOR_RISC, CLASSI_FIN, EVOLUCAO) |>
  rename(cod_mun = CO_MUN_NOT,
         uf = SG_UF, 
         data = DT_NOTIFIC, 
         sexo = CS_SEXO, 
         idade = NU_IDADE_N,
         comorbidade = FATOR_RISC,
         srag = CLASSI_FIN,
         obito = EVOLUCAO)
df_srag = df_srag |>
  mutate(
    data = 
      stringr::str_replace_all(data, '/', '-') |>
      lubridate::dmy(),
    cod_uf = cod_mun |>
      as.character() |>
      stringr::str_sub(1, 2) |>
      as.numeric()
    ) |>
  relocate(cod_uf, .before = uf) |>
  select(-uf) 


df_srag |>
  mutate(
    comorbidade = 
      case_when(comorbidade == 1 ~ 1,
                comorbidade == 2 ~ 0 )) |>
  mutate(influenza = NA,
         covid = NA,
         outros = NA) |>
  mutate(
    influenza = 
      case_when(srag == 1 ~ 1,
                .default = 0),
    covid = 
      case_when(srag == 5 ~ 1,
                .default = 0),
    outros = 
      case_when(srag == 2 | srag == 3 | srag == 4  ~ 1,
                .default = 0))
# A tibble: 226,763 x 11
   cod_mun cod_uf data       sexo  idade comorbidade  srag obito influenza covid
     <dbl>  <dbl> <date>     <chr> <dbl>       <dbl> <dbl> <dbl>     <dbl> <dbl>
 1  310150     31 2023-01-18 M        75           1     4     1         0     0
 2  330630     33 2023-01-04 M        67           1     4     1         0     0
 3  352530     35 2023-01-08 F        72           1     5     1         0     1
 4  350010     35 2023-01-23 F        46           0     4     1         0     0
 5  350950     35 2023-02-05 M        71           0     4     1         0     0
 6  330330     33 2023-02-06 F         7           0     4     1         0     0
 7  292740     29 2023-02-04 F         1           1     4     2         0     0
 8  410180     41 2023-02-22 F         4           0     2     1         0     0
 9  270430     27 2023-02-13 M         8           1     4     1         0     0
10  411390     41 2023-01-05 F        86           0     4     1         0     0
# i 226,753 more rows
# i 1 more variable: outros <dbl>
# 
#   pivot_longer(cols = c(influenza, covid, outros),
#                names_to = 'tipo_srag',
#                values_to = 'freq')